<script setup>
import { Reads, Writes } from '@/Utils/axiosHelper'
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()

// 表单数据
const formData = reactive({
  eweId: route.params.id,
  earSignal: '',
  electronicEarTag: '',
  variety: null,
  geneRank: null,
  fatherNumber: null,
  motherNumber: null,
  dateofBirth: '',
  entryDate: '',
  placeOfBirth: null,
  birthWeight: '',
  note: ''
})

// 下拉选项
const varietyOptions = [
  { id: 1, name: '萨福克' },
  { id: 2, name: '多赛特' },
  { id: 3, name: '美利奴' },
  { id: 4, name: '波尔山羊' },
  { id: 5, name: '其他' }
]

const fatherNumberOptions = [
  { id: 1, name: '父耳号-001' },
  { id: 2, name: '父耳号-002' },
  { id: 3, name: '父耳号-003' },
  { id: 4, name: '父耳号-004' },
  { id: 5, name: '父耳号-005' }
]

const motherNumberOptions = [
  { id: 1, name: '母耳号-001' },
  { id: 2, name: '母耳号-002' },
  { id: 3, name: '母耳号-003' },
  { id: 4, name: '母耳号-004' },
  { id: 5, name: '母耳号-005' }
]

const geneRankOptions = [
  { id: 1, name: 'A级' },
  { id: 2, name: 'B级' },
  { id: 3, name: 'C级' },
  { id: 4, name: 'D级' }
]

const placeOfBirthOptions = [
  { id: 1, name: '场地A' },
  { id: 2, name: '场地B' },
  { id: 3, name: '场地C' },
  { id: 4, name: '场地D' }
]

const loading = ref(false)

// 获取牲畜档案详情
const fetchLivestockDetail = async () => {
  const id = route.params.id
  if (!id) {
    alert('未找到牲畜档案ID')
    router.push('/livestock-list')
    return
  }

  loading.value = true
  try {
    const response = await Reads.get(`/Management/GetEweFileById`,{
      params: {
        eweId: id
      }
    })
    
    if (response.data && response.data.code === 400) {
      console.log(response);
      const data = response.data.data
      // 填充表单数据
      Object.keys(formData).forEach(key => {
        if (data[key] !== undefined) {
          formData[key] = data[key]
        }
      })
    } else {
      alert('获取牲畜档案详情失败：' + (response.data?.message || '未知错误'))
      router.push('/livestock-list')
    }
  } catch (error) {
    console.error('获取牲畜档案详情失败:', error)
    alert('获取详情失败：' + (error.response?.data?.message || '网络错误'))
    router.push('/livestock-list')
  } finally {
    loading.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  const id = route.params.id
  if (!id) {
    alert('未找到牲畜档案ID')
    return
  }

  // 表单验证
  if (!formData.earSignal.trim()) {
    alert('请输入耳号')
    return
  }
  if (!formData.electronicEarTag.trim()) {
    alert('请输入电子耳标号')
    return
  }

  loading.value = true
  try {
    const response = await Writes.put(`/Management/UpdateEweFile`, formData)
    
    if (response.data && response.data.code === 300) {
      alert('修改成功！')
      router.push('/livestock-list')
    } else {
      alert('修改失败：未知错误')
    }
  } catch (error) {
    console.error('修改牲畜档案失败:', error)
    alert('修改失败')
  } finally {
    loading.value = false
  }
}

// 返回列表
const goBack = () => {
  router.push('/livestock-list')
}

// 重置表单
const handleReset = () => {
  fetchLivestockDetail()
}

// 格式化显示函数
const formatVariety = (value) => {
  const option = varietyOptions.find(item => item.id === value)
  return option ? option.name : value
}

const formatFatherNumber = (value) => {
  const option = fatherNumberOptions.find(item => item.id === value)
  return option ? option.name : value
}

const formatMotherNumber = (value) => {
  const option = motherNumberOptions.find(item => item.id === value)
  return option ? option.name : value
}

const formatGeneRank = (value) => {
  const option = geneRankOptions.find(item => item.id === value)
  return option ? option.name : value
}

const formatPlaceOfBirth = (value) => {
  const option = placeOfBirthOptions.find(item => item.id === value)
  return option ? option.name : value
}

const formatDate = (dateString) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleDateString('zh-CN')
}

// 组件挂载时获取数据
onMounted(() => {
  fetchLivestockDetail()
})
</script>

<template>
  <div class="livestock-edit-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>编辑牲畜档案</h2>
      <button class="btn btn-primary" @click="goBack">
        <svg class="btn-icon" viewBox="0 0 24 24" fill="currentColor">
          <path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"/>
        </svg>
        返回列表
      </button>
    </div>

    <!-- 编辑表单 -->
    <div class="form-section">
      <el-form :model="formData" label-width="120px" v-loading="loading">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="耳号" required>
              <el-input v-model="formData.earSignal" placeholder="请输入耳号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="电子耳标号" required>
              <el-input v-model="formData.electronicEarTag" placeholder="请输入电子耳标号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="品种">
              <el-select v-model="formData.variety" placeholder="请选择品种" clearable>
                <el-option
                  v-for="option in varietyOptions"
                  :key="option.id"
                  :label="option.name"
                  :value="option.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="父耳号">
              <el-select v-model="formData.fatherNumber" placeholder="请选择父耳号" clearable>
                <el-option
                  v-for="option in fatherNumberOptions"
                  :key="option.id"
                  :label="option.name"
                  :value="option.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="母耳号">
              <el-select v-model="formData.motherNumber" placeholder="请选择母耳号" clearable>
                <el-option
                  v-for="option in motherNumberOptions"
                  :key="option.id"
                  :label="option.name"
                  :value="option.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="基因等级">
              <el-select v-model="formData.geneRank" placeholder="请选择基因等级" clearable>
                <el-option
                  v-for="option in geneRankOptions"
                  :key="option.id"
                  :label="option.name"
                  :value="option.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="出生日期">
              <el-date-picker
                v-model="formData.dateofBirth"
                type="date"
                placeholder="选择出生日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="出生重量(kg)">
              <el-input-number
                v-model="formData.birthWeight"
                :precision="2"
                :step="0.1"
                :min="0"
                placeholder="请输入出生重量"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="入场日期">
              <el-date-picker
                v-model="formData.entryDate"
                type="date"
                placeholder="选择入场日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="出生场地">
              <el-select v-model="formData.placeOfBirth" placeholder="请选择出生场地" clearable>
                <el-option
                  v-for="option in placeOfBirthOptions"
                  :key="option.id"
                  :label="option.name"
                  :value="option.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                v-model="formData.note"
                type="textarea"
                :rows="3"
                placeholder="请输入备注信息"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="loading">
            <svg class="btn-icon" viewBox="0 0 24 24" fill="currentColor">
              <path d="M17 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V7l-4-4zm-5 16c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3zm3-10H5V5h10v4z"/>
            </svg>
            保存修改
          </el-button>
          <el-button @click="handleReset">
            <svg class="btn-icon" viewBox="0 0 24 24" fill="currentColor">
              <path d="M12 5V1L7 6l5 5V7c3.31 0 6 2.69 6 6s-2.69 6-6 6-6-2.69-6-6H4c0 4.42 3.58 8 8 8s8-3.58 8-8-3.58-8-8-8z"/>
            </svg>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
.livestock-edit-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.page-header h2 {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.form-section {
  background: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.btn {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  text-decoration: none;
}

.btn-primary {
  background-color: #409eff;
  color: white;
}

.btn-primary:hover {
  background-color: #66b1ff;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.3);
}

.btn-icon {
  width: 16px;
  height: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }
}

/* 表单样式优化 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-input__wrapper) {
  border-radius: 6px;
}

:deep(.el-select__wrapper) {
  border-radius: 6px;
}

:deep(.el-textarea__inner) {
  border-radius: 6px;
}
</style>